#include "Network.h"
#include <stdio.h>
#include <stdlib.h>

SpideyHttp::SpideyHttp(SpideyWindow *window, int howDeep)
{
    if(howDeep < 0) {
        return; }

    http = new QHttp();
    connect(http, SIGNAL(done(bool)),
            this, SLOT(addToScene(bool)));

    TheDoc = new QDomDocument();

    parentWindow = window;

    depthLeft = howDeep;

/*    progressDialog = new QProgressDialog(this);
    connect(http, SIGNAL(dataReadProgress(int, int)),
            this, SLOT(updateDataReadProgress(int, int)));
*/

    connect(this, SIGNAL(AllDone()),
            this, SLOT(destructo()));
}

void SpideyHttp::downloadWikiPage(const QString & pageName)
{
    http->setHost("en.wikipedia.org");
    if(pageName.startsWith("/wiki/")) {
        http->get(pageName);
    }
    else {
        http->get("/wiki/" + pageName);
    }

/*    progressDialog->setLabelText(tr("Downloading %1.").arg(pageName));
    QPushButton *button = new QPushButton(tr("Cancel"));
    button->setEnabled(false);
    progressDialog->setCancelButton(button);
    progressDialog->show();
*/
}

int ijk = 1;
int lmn = 0;

void SpideyHttp::addToScene(bool error)
{
    if(error) {
        QMessageBox::information(this, tr("HTTP"),
                                tr("Download failed: %1.")
                                .arg(http->errorString()));
        return;
     }
     lmn = lmn+1;

    // add this page to SpideyWindow
    srand(QTime::currentTime().msec());
    //int randX = (((double)rand()/((double)RAND_MAX + (double)1)) * 600 - 300) * ijk;
    //int randY = (((double)rand()/((double)RAND_MAX + (double)1)) * 600 - 300) * ijk;
    int randX = lmn - 400;
    int randY = ijk - 300;
    node *nd = new node(1, randX, randY, parentWindow);
    parentWindow->addNode(nd);

    if(depthLeft != 0) {
        // load page into TheDoc
        //QString tempString(http->readAll());
        /*QString errString("?? no error ??");
        int errLine = 999;
        int errColumn = 999;    //tempString
        if(!TheDoc->setContent(http->readAll(), &errString, &errLine, &errColumn)) {
            QMessageBox::information(this, tr("DOM"),
                                      tr("DOM shit failled: %1 - line %2 - column %3")
                                      .arg(errString).arg(errLine).arg(errColumn));
        }*/
        if(!TheDoc->setContent(http->readAll())) {
            QMessageBox::information(this, tr("DOM"), tr("Shit failed"));
            return;
        }

        //QDomElement root = TheDoc->documentElement();
/*      // doesn't seem to do anything...
        QDomNodeList pre(root.elementsByTagName("div"));
        for(unsigned int k = 0; k < pre.length(); k++) {
            if(pre.at(k).toElement().attribute("id") == "contentStub") {
                pre.at(k).parentNode().removeChild(pre.at(k));
                k--;
            }
            if(pre.at(k).toElement().attribute("id") == "jump-to-nav") {
                pre.at(k).parentNode().removeChild(pre.at(k));
                k--;
            }
            if(pre.at(k).toElement().attribute("class") == "printfooter") {
                pre.at(k).parentNode().removeChild(pre.at(k));
                k--;
            }
        }
*/
        QDomNodeList list(TheDoc->elementsByTagName("a"));

        // filter URL list
        for(unsigned int i = 0; i < list.length(); i++) {
            if(list.at(i).toElement().hasAttribute("href")) {
                if(!list.at(i).toElement().attribute("href").startsWith("/wiki/")) {    // if href does not link to page within wikipedia
                    list.at(i).parentNode().removeChild(list.at(i));        // then delete it
                    i--;
                }
            }
            else {          // if it has no href for some reason, delete it
                list.at(i).parentNode().removeChild(list.at(i));
                i--;
            }
        }

        // loop through links, create
        QString linksString;
        for(unsigned int j = 0; j < list.length(); j++) {
            if(list.at(j).toElement().hasAttribute("href")) {
                SpideyHttp *tmpHttp = new SpideyHttp(parentWindow, depthLeft - 1);
                tmpHttp->downloadWikiPage(list.at(j).toElement().attribute("href"));
                linksString += list.at(j).toElement().attribute("href") += '\n';
                ijk = j;
/*                node *n = new node(1, (depth+1)*j-300, (depth+1)*j-300);
                parentScene->addItem(n);*/
                //**/delete tmpHttp;
            }
        }

/*        QTextEdit *linksEdit = new QTextEdit();
        linksEdit->setPlainText(tempString);
        linksEdit->show();
*/
    }
    emit AllDone(true);
}

/*
void SpideyHttp::updateDataReadProgress(int bytesRead, int totalBytes)
{
    progressDialog->setMaximum(totalBytes);
    progressDialog->setValue(bytesRead);
}
*/

void SpideyHttp::destructo()
{
    delete http;
    //delete progressDialog;
    delete TheDoc;
    delete this;
}

/* tests */
/*  // make sure it downloaded and the data can be accessed
    QString tempString(http->readAll());
    QTextEdit *fileEdit = new QTextEdit();
    fileEdit->setPlainText(tempString);
    fileEdit->show();
//*/

